package org.niugang.coding.interceptor;


import org.apache.commons.lang3.StringUtils;
import org.niugang.coding.dto.UserInfo;
import org.niugang.coding.enums.ExceptionEnum;
import org.niugang.coding.exception.ServiceException;
import org.niugang.coding.oauth.JwtProperties;
import org.niugang.coding.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 认证校验拦截器
 *
 * @author Created by niugang on 2019/1/11/16:35
 */
//@EnableConfigurationProperties(JwtProperties.class)
public class AuthorizedCheckInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties props;

    //保存当前请求线程副本
    private static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();

    public AuthorizedCheckInterceptor() {
        super();
    }

    public AuthorizedCheckInterceptor(JwtProperties props) {
        this.props = props;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            //未授权
            throw new ServiceException(ExceptionEnum.UNAUTHORIZED);
        }
        //用户已登录，获取用户信息
        try {
            UserInfo userInfo = JwtUtils.getUserInfo(props.getPublicKey(), token);
            //放入线程域中
            threadLocal.set(userInfo);
            return true;
        } catch (Exception e) {
            //抛出异常，未登录
            throw new ServiceException(ExceptionEnum.UNAUTHORIZED);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //一次请求完成之后，从线程域中删除用户信息
        threadLocal.remove();
    }

    /**
     * 获取登陆用户信息
     *
     * @return UserInfo
     */
    public static UserInfo getUserInfo() {
        return threadLocal.get();
    }
}
